class HitTestDistance extends egret.DisplayObjectContainer {
    private ball1: Ball
    private ball2: Ball

    private draggingBall: Ball

    public constructor() {
        super()
        this.once(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this)
    }

    private onAddToStage(): void {
        this.ball1 = new Ball()
        this.ball1.x = this.stage.stageWidth / 2
        this.ball1.y = this.stage.stageHeight / 2
        this.ball2 = new Ball()
        this.ball1.touchEnabled = true
        this.ball2.touchEnabled = true
        this.addChild(this.ball1)
        this.addChild(this.ball2)
        this.stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTouchStart, this)
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this)
    }

    private onEnterFrame() {
        let { isHit } = this.hitTestBall(this.ball1, this.ball2)
        if (isHit) {
            console.log("HIT")
        }
    }

    private onTouchStart(evt: egret.TouchEvent) {
        if (evt.target instanceof Ball) {
            this.draggingBall = evt.target
        }
        this.stage.addEventListener(egret.TouchEvent.TOUCH_END, this.onTouchEnd, this)
        this.stage.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.onTouchMove, this)
    }

    private onTouchEnd(evt: egret.TouchEvent) {
        this.draggingBall = null
        this.stage.removeEventListener(egret.TouchEvent.TOUCH_END, this.onTouchEnd, this)
        this.stage.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.onTouchMove, this)
    }

    private onTouchMove(evt: egret.TouchEvent) {
        if (this.draggingBall == null && evt.target instanceof Ball) {
            this.draggingBall = evt.target
        }

        if (this.draggingBall == null) {
            return
        }

        this.draggingBall.x = evt.stageX
        this.draggingBall.y = evt.stageY
    }

    private hitTestBall(a: Ball, b: Ball): { isHit: boolean, angle: number } {
        let dx = b.x - a.x
        let dy = b.y - a.y
        let point = egret.Point.create(dx, dy)
        let isHit: boolean = false
        if (point.length < a.radius + b.radius) {
            isHit = true
        }
        egret.Point.release(point)
        return { isHit, angle: Math.atan2(dy, dx) }
    }
}